import api from '../../api/index';
import { sdk } from '../../config/sdk';

Page({
  data: {
    loading: true
  },
  onLoad: function () {
    const self = this;
    const timer = setTimeout(() => {
      self.setData({
        tips: true
      });
      clearTimeout(timer);
    }, 5500);
  },
  
  onShow() {
    this.getUserInfo();
  },

  // 获取用户信息
  async getUserInfo() {
    const { code, message, data } = await sdk.request({ url: api.getUserInfo, method: 'GET' });
    if (code != 1000) return this.$error(message);
    this.setData({
      userInfo: data,
      loading: false
    });
  },

  // 修改头像
  avatar() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      sizeType: ['compressed'],
      success: res => {
        sdk.uploadFile({ url: api.upload, filePaths: res.tempFiles })
          .then(async res => {
            const { code, message, data } = await sdk.request({ url: api.avatar, data: { avatar: res[0] } });
            if (code != 1000) return this.$error(message);
            let userInfo = this.data.userInfo;
            userInfo.avatar = res[0];
            this.$success(message);
            this.setData({ 
              userInfo 
            });
          })
      }
    });
  },

  async upNickName(e) {
    if (!e.detail.value) return wx.showToast({ title: '昵称不能为空', icon: 'error', mask: true });
    const { code, message, data } = await sdk.request({ url: api.nickName, data: { nickname: e.detail.value} })
    if (code != 1000) return this.$error(message);
    let userInfo = this.data.userInfo;
    userInfo.nickname = e.detail.value;
    this.setData({ 
      userInfo
    });
    this.$success(message);
  },

  // 学生认证
  auth() {
    this._toPath('pages/auth/index');
  }
})